// import { defineEmits } from 'vue';
import { ref, reactive, computed, defineEmits, onMounted, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { emitter } from "@/utils/mitt";
export function usescreen() {
  const MZData = [{ "id": "Gender", "text": "性别" }, { "id": "Age", "text": "年龄" }, { "id": "JobType", "text": "工作类型" }, { "id": "RealEstate", "text": "房产状况" }, { "id": "FamilyStatus", "text": "婚姻状况" }, { "id": "WorkStability", "text": "工作稳定性" }, { "id": "ConsumptionLevel", "text": "消费水平" }, { "id": "IncomeLevel", "text": "收入水平" }, { "id": "OnlineShoppingFrequency", "text": "网购频率" }]
  const TJData = [{ id: "1", text: ">" }, { id: "2", text: "=" }, { id: "3", text: "<" }, { id: "4", text: ">=" }, { id: "5", text: "<=" }, { id: "6", text: "≠" }]
  const BHData = [{ id: "1", text: "包含" }, { id: "2", text: "不包含" }];
  const CZData = [{ id: "4", text: "客户属性满足" }];
  const selData = {
    Gender: [{ "id": "1", "text": "男" }, { "id": "2", "text": "女" }],
    JobType: [{ "id": "1", "text": "公务员" }, { "id": "2", "text": "事业单位" }, { "id": "3", "text": "国有企业" }, { "id": "4", "text": "外企" }, { "id": "5", "text": "私营企业" }, { "id": "6", "text": "个体工商户" }, { "id": "7", "text": "自由职业者" }, { "id": "8", "text": "无" }],
    RealEstate: [{ "id": "1", "text": "有房产" }, { "id": "2", "text": "无房产" }],
    FamilyStatus: [{ "id": "1", "text": "未婚" }, { "id": "2", "text": "已婚" }, { "id": "3", "text": "已婚有一子女" }],
    WorkStability: [{ "id": "1", "text": "不稳定" }, { "id": "2", "text": "较稳定" }, { "id": "3", "text": "稳定" }],
    ConsumptionLevel: [{ "id": "1", "text": "高" }, { "id": "2", "text": "中" }, { "id": "3", "text": "低" }],
    IncomeLevel: [{ "id": "1", "text": "一般" }, { "id": "2", "text": "中等" }, { "id": "3", "text": "较好" }, { "id": "4", "text": "好" }, { "id": "5", "text": "优" }],
    OnlineShoppingFrequency: [{ "id": "1", "text": "高" }, { "id": "2", "text": "中" }, { "id": "3", "text": "低" }],
  };
  const mType = [{ "id": "1", "text": "文本框" }, { "id": "2", "text": "大于、小于、等于" }, { "id": "3", "text": "包含、不包含" }];
  const endData = ref<any>([]);
  const myJSonar = ref<any>();

  // methods
  function selectFn(e: { target: { value: any; }; }, b: string | number, d: string | number) {
    // console.log(e.target.selectedIndex) // 选择项的index索引
    //console.log(e.target.value) // 选择项的value
    var val = e
    var typ = 1;
    var name = '';
    if (val == "Gender") {
      typ = 3;
      name = "Gender"
    } else if (val == 'Age') {
      typ = 2
    } else if (val == "JobType") {
      typ = 3
      name = "JobType";
    } else if (val == 'RealEstate') {
      typ = 3
      name = "RealEstate";
    } else if (val == "FamilyStatus") {
      typ = 3
      name = "FamilyStatus";
    } else if (val == "WorkStability") {
      typ = 3
      name = "WorkStability";
    } else if (val == "ConsumptionLevel") {
      typ = 3
      name = "ConsumptionLevel";
    } else if (val == 'IncomeLevel') {
      typ = 3
      name = 'IncomeLevel'
    } else if (val == "OnlineShoppingFrequency") {
      typ = 3
      name = "OnlineShoppingFrequency"
    } else {
      typ = null
    }
    endData.value[b].data[d].rather = '';
    endData.value[b].data[d].times = '';
    endData.value[b].data[d].rather2 = '';
    endData.value[b].data[d].times2 = '';
    endData.value[b].data[d].selectMore = '';
    endData.value[b].data[d].mType = typ;
    endData.value[b].data[d].mName = name;
  }

  function selectShow(e: any, b: string | number, d: string | number) {
    let isSelect = endData.value[b].data[d].isSelect;
    endData.value[b].data[d].isSelect = !isSelect
  }
  //活跃次数select下拉选择
  function selectFn2(e: { target: { [x: string]: { value: string; }; }; }, b: string | number, d: string | number) {
    endData.value[b].data[d].selectMore = '';
    let selectd = endData.value[b].data[d].times;
    selectd.forEach((item, i) => {
      let dun = "";
      if (i) {
        dun = "|"
      }
      endData.value[b].data[d].selectMore += dun + e.target[item].innerText;
      endData.value[b].data[d].mVal += dun + e.target[item].value
    })
    return false;
  }

  // type  点击按钮类型   { id: "1", text: "做过" }, { id: "2", text: "新增于" }, { id: "3", text: "活跃次数" }, { id: "4", text: "客户属性满足" }
  // id  并且对应的下标
  // ids 并且下面子类，或者对应的按钮
  function addItem(type: any, id: number, ids: any) {
    verifyNum();
    let obj = { type: type, term: '', rather: '', times: '', rather2: '', times2: '', selectMore: '', isSelect: '', mType: '', mName: '', mVal: '' };
    if (type == 2) {
      obj["term"] = 1;
    }
    if (type == 3) {
      //console.log(this.selectArrs.arr3);
      if (selectArrs.arr3.length >= 6) {
        return false;
      }
    }
    // 如果是非子类按钮点击时
    if (!ids && ids != 0) {
      id = id + 1;
    }

    if (endData.value[id]) {   //判断当前数组是否存在
      endData.value[id].data.push(obj)
    } else {
      endData.value.push({
        data: [obj]
      })
    }
  }

  /**
  * 移除
  * @param {number | string} id 当前点击数组对应的项的下标
  * @param {number | string} ids 当前点击数组对应的项子类那一项的下标
  */
  function removeItem(id: string | number, ids: any) {
    if (endData.value[id].data.length == 1) {  //如果是最后一条直接删除当前数组那一项
      endData.value.splice(id, 1);    //删除对应数据
    } else {
      //删除数组子类下的项
      endData.value[id].data.splice(ids, 1);    //删除对应数据
    }
  }

  //点击确定的事件
  function setChoose() {
    verifyNum();
    let arr = [];
    let isstate: number;
    endData.value.forEach((item: { data: any[]; }, index: number) => {
      let index2 = index + 1;
      item.data.forEach((a, i) => {
        isstate = 1
        let i2 = '';
        if (i) {
          i2 = i
        }
        isstate = VerifyContent(a)
        a["times"] = a["times"].toString();
        a["id"] = index2 + '' + i2;
        arr.push(a);
      });
    });
    let strArr = JSON.stringify(arr);
    if (strArr == "[]" || !isstate) { ElMessage.warning("请设置创建任务筛选条件！"); return; }
    emitter.emit("saveCustomer", strArr)
  }

  function VerifyContent(a) {
    let isstate = 1;
    if (a.mType == '' && a.mName == '') isstate = 0;
    if (a.mType == 2 && a.mName == 'jypl') {
      if (a.daily === "") isstate = 0;
      if (a.rather === "") isstate = 0;
      if (a.times === "") isstate = 0;
    }

    if (a.mType == 2 && a.mName != 'jypl') {
      if (a.rather === "") isstate = 0;
      if (a.times === "") isstate = 0;
    }
    if (a.mType == 3) {
      if (a.rather === "") isstate = 0;
      if (a.selectMore === "" || a.selectMore?.length === 0) isstate = 0;
    }
    return isstate
  }

  emitter.on("CreateCustomer", (row) => { setChoose() })

  onBeforeUnmount(() => {
    emitter.off("CreateCustomer")
  })
  function onCreate() {
    verifyNum();
    let arr = [];
    endData.value.forEach((item, index) => {
      let index2 = index + 1;
      item.data.forEach((a, i) => {
        let i2 = '';
        if (i) {
          i2 = i
        }
        a["times"] = a["times"].toString();
        a["id"] = index2 + '' + i2;
        arr.push(a);
      });
    });
    let strArr = JSON.stringify(arr);
    if (strArr == "[]") { ElMessage.warning("请设置筛选条件！"); return; }
    myJSonar.value = strArr;//筛选条件
    // onOpenCreate();//打开创建客户群窗口

  }

  function clearChoose() {
    endData.value = [];
    // mini.get("UserGroup").setValue(0);
  }

  function verifyNum() {
    endData.value.forEach((item, index) => {
      item.data.forEach((a, i) => {
        if (Number(a.times)) {
          a.times = Number(a.times);
        } else {
          a.times = 0;
        }
        if (Number(a.times2)) {
          a.times2 = Number(a.times2);
        } else {
          a.times2 = 0;
        }
      });
    });
  }

  /**
   * 输入框对输入数字的处理
   * @param {obj} event js事件对象
   * @param {string|number} b 一级数组子类下标
   * @param {string|number} d 一级子类下的子类（二级下标）
   * @param {string} name 需要更改的字段name名
   * @param {string|number} type 需要处理的类型，type=1 正数和小数，type=2 正整数，type为空或其他 数字（包含小数、负数）
   * @param {number} max 输入框允许输入的最大值，这里默认是180
   * @returns
   */
  function changeNum(event, b, d, name, type, max = 180) {
    //响应鼠标事件，允许左右方向键移动
    event = window.event || event;
    if (event.keyCode == 37 || event.keyCode == 39) {
      return;
    }
    let val = event.target.value;
    let t = val.charAt(0);
    let t2 = val.charAt(1);
    if (type == 2) {
      val = val.replace(/^[^\d]+/g, ''); //非正整数都替换为空
      if (Number(val) > max) {
        val = max;
      }
    } else {
      //先把非数字的都替换掉，除了数字和.
      val = val.replace(/[^\d.]/g, "");
      //必须保证第一个为数字而不是.
      val = val.replace(/^\./g, "");
      //保证只有出现一个.而没有多个.
      val = val.replace(/\.{2,}/g, ".");
      //保证.只出现一次，而不能出现两次以上
      val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      //console.log(t);
      //console.log(t2);
      if (t == 0 && t2 == 0) {
        val = 0;
      }
      if (val.toString().length > 10) {
        val = Number(val).toFixed(8)
      }
      //console.log(val);
      if (Number(val) > max) {
        val = max;
      }
      if (type == 1) {

      } else {
        //如果第一位是负号，则允许添加   如果不允许添加负号 可以把这块注释掉
        if (t == '-') {
          val = '-' + val;
        }
      }

    }
    var linReg = /^[0]+$/gi;    //全部都为0
    var ax = endData.value[b].data[d]
    if (linReg.test(val)) {
      ax[name] = 0
    } else {
      ax[name] = val
    }
  }

  function clearNoNum(obj) {
    if (!(/[^0]/gi.test(obj.value))) {
      return obj.value = 0;
    }
  }

  const selectArrs = computed(() => {
    let arr1 = [1], arr2 = [2], arr3 = [3], arr4 = [4];
    return { arr1, arr2, arr3, arr4 };
  })
  return {
    MZData,
    TJData,
    BHData,
    CZData,
    selData,
    mType,
    endData,
    selectArrs,
    addItem,
    selectFn,
    selectFn2,
    selectShow,
    removeItem,
    setChoose,
    onCreate,
    clearChoose,
    clearNoNum,
    changeNum
  }
}
